//
//  NetworkTools.swift
//  练习-04-Swift AFN
//
//  Created by co on 16/2/27.
//  Copyright © 2016年 王南侠. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络请求的枚举类型，Swift中的枚举可以指定不同的数据类型
enum CZRequestMothod:String{
    case GET = "GET"
    case POST = "POST"
}


class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    let appkey = "978609048"
    let appSecret = "548b731599e198352c2f9a9b7cb24c6c"
    let redirectUri = "http://www.baidu.com"

    /// 单例
    static let sharedTools: NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        
        // 设置 AFN 网络“请求”超时
        tools.requestSerializer.timeoutInterval = 10
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
       
        // 将 json 中的NULL 值过滤 有些第三方框架在做字典转模型时，如果遇到 NULL就会崩溃
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
        
        // 启动连接状态监听 -通过通知中心发布的
        tools.reachabilityManager.startMonitoring()
        
        return tools
    }()
    
    
    deinit {
        // 停止网络连接状态的监听
        reachabilityManager.stopMonitoring()
        
    }
    
    /// 判断当前网络是否能够连接
    var reachebe:Bool {
        return reachabilityManager.reachable
    }
    
    func request(method:CZRequestMothod, URLString: String,parameters: [String: AnyObject]?, finshed: (result: [String: AnyObject]?)->()){
        
        // 成功回调
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            if let result = responseObject as? [String: AnyObject]{
                
                finshed(result: result)
            } else {
                
                
                print("数据格式错误")
                finshed(result: nil)
            }
            
        }
        
        // 失败回调
        let failure = { (task: NSURLSessionDataTask?,error: NSError) -> Void in
                print("网络请求错误\(error)")
                finshed(result: nil)
        }
        

        if method == .GET{
            // GET 请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            // POST 请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
